package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.User;
import com.example.form.LoginBody;
import com.example.result.Message;
import com.example.result.R;
import com.example.result.Code;
import com.example.service.IUserService;
import com.example.utils.JWTUtils;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Date 2022/9/27
 * @Description
 */
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JWTUtils jwtUtils;

    @PostMapping("/login")
    public R login(@Validated @RequestBody LoginBody loginBody, HttpServletResponse response) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        User user = userService.getUser(username);
        Assert.notNull(user, Message.LOGIN_USERNAME_ERROR);

        if (!user.getPassword().equals(password)) {
            return R.fail(Message.LOGIN_PASSWORD_ERROR);
        }
        if ("0".equals(user.getStatus())) {
            return R.fail(Message.LOGIN_STATUS_ERROR);
        }

        String token = jwtUtils.createToken(user.getId());
        response.addHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return R.success(
                userService.getOne(new QueryWrapper<User>().eq("username", username)),
                Message.LOGIN_SUCCESS
        );

    }


}
